package com.zwj.se.thread;

import java.util.concurrent.*;

/**
 * 实现 Callable 接口，自定义线程
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/8/22 11:03
 */
public class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        //模拟计算需要 1 秒
        Thread.sleep(1000);
        return 2;
    }

    public static void main(String[] args) {
        fun2();
    }

    private static void fun2() {
        //默认线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        FutureTask<Integer> futureTask = new FutureTask<>(new Task());
        executorService.submit(futureTask);
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    private static void fun1() {
        //默认线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //执行线程
        Future<Integer> submit = executorService.submit(new Task());
        //获取结果
        // 注意调用get方法会阻塞当前线程，直到得到结果。
        // 所以实际编码中建议使用可以设置超时时间的重载get方法。
        Integer result = null;
        try {
            result = submit.get();
        } catch (InterruptedException | ExecutionException e ) {
            throw new RuntimeException(e);
        }
        System.out.println(result);
    }
}
